package com.xb.cloud.order.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.aspectj.util.LangUtil.ProcessController.Thrown;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xb.cloud.common.JsonUtils;
import com.xb.cloud.common.client.bo.UpdateInfo;
import com.xb.cloud.common.constant.DbConstants;
import com.xb.cloud.common.util.BeanUtils;
import com.xb.cloud.order.model.ProductStock;
import com.xb.cloud.order.model.ProductStockExample;
import com.xb.cloud.order.model.ProductStockExample.Criteria;
import com.xb.cloud.order.model.mapper.ProductStockMapper;
import com.xb.cloud.order.service.client.ProductStockService;
import com.xb.cloud.order.service.client.bo.SoSkuSummeryBo;
import com.xb.cloud.product.merchant.service.client.bo.EndMerchantUserBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductSkuBo;
import com.xb.cloud.service.client.ServiceReturnCodes;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;
import com.xb.cloud.user.service.client.bo.ProductSkuStockBo;

/**
 * 库存操作类 ， 目前实现库存精确到product+shop (既sku)级别
 * 
 *
 */
@Service
public class ProductStockServiceImpl extends AbstractService implements ProductStockService {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProductStockServiceImpl.class);

	@Resource
	private ProductStockMapper productStockMapper;
	
	/**
	 * 插入库存(shop+product)
	 * 
	 * @param endMerchantUserBo
	 * @param productId
	 * @param stockNum
	 * @param warehouseId
	 * @return
	 */
	@Override
	public ServiceReturnInfo createProductStock(EndMerchantUserBo endMerchantUserBo, Long productId, Long stockNum,
			Long warehouseId) {
		ProductStock stock = new ProductStock();

		Long generateKey = ipKeyGenerator.generateKey();
		stock.setId(generateKey);
		stock.setCompanyId(endMerchantUserBo.getCompanyId());
		stock.setMerchantId(endMerchantUserBo.getMerchantId());
		stock.setShopId(endMerchantUserBo.getShopId());
		stock.setProductId(productId);// productId
		stock.setRealStockNum(stockNum);// 真实库存
		stock.setRealFrozenStockNum(0L);// 冻结库存
		stock.setWarehouseId(warehouseId);//

		stock.setCreateTime(timeService.getDate());
		stock.setCreateUserId(endMerchantUserBo.getId());
		stock.setCreateUserName(endMerchantUserBo.getLoginName());
		int insertSelective = productStockMapper.insertSelective(stock);
		if (insertSelective <= 0) {
			LOGGER.error("插入ProductStock 失败" + JsonUtils.beanToJson(stock));
			throw new RuntimeException("插入ProductStock失败");
		}
		return ServiceReturnUtils.success(generateKey);
	}

	/**
	 * 根据， 产品+店铺+仓库 的id 查询对应的库存记录 product_stock
	 * 
	 * @return
	 */
	public ServiceReturnInfo getProductStockByProductShopWarehouse(Long productId, Long shopId, Long warehouseId) {
		ProductStockExample productStockExample = new ProductStockExample();
		Criteria stockQueryCriteria = productStockExample.createCriteria();

		stockQueryCriteria.andProductIdEqualTo(productId);
		stockQueryCriteria.andShopIdEqualTo(shopId);
		stockQueryCriteria.andWarehouseIdEqualTo(warehouseId);

		List<ProductStock> productStockList = productStockMapper.selectByExample(productStockExample);
		if (productStockList != null && productStockList.size() > 0) {
			ProductStock productStock = productStockList.get(0);
			return ServiceReturnUtils.success(BeanUtils.newAndCopyProperties(ProductSkuStockBo.class, productStock));
		} else {
			return ServiceReturnUtils.success();
		}
	}

	/**
	 * 根据，productIdList+店铺+仓库 的id 查询对应的库存记录 product_stock
	 * 
	 * @return
	 */
	public ServiceReturnInfo getProductStockByProductListShopWarehouse(List<Long> productIdList, Long shopId,
			Long warehouseId) {
		ProductStockExample productStockExample = new ProductStockExample();
		Criteria stockQueryCriteria = productStockExample.createCriteria();

		stockQueryCriteria.andProductIdIn(productIdList);
		stockQueryCriteria.andShopIdEqualTo(shopId);
		stockQueryCriteria.andWarehouseIdEqualTo(warehouseId);

		List<ProductStock> productStockList = productStockMapper.selectByExample(productStockExample);
		if (productStockList != null && productStockList.size() > 0) {
			Map<Long, ProductSkuStockBo> skuStockMap = new HashMap<Long, ProductSkuStockBo>();
			for (ProductStock stock : productStockList) {
				ProductSkuStockBo stockBo = BeanUtils.newAndCopyProperties(ProductSkuStockBo.class, stock);
				skuStockMap.put(stockBo.getProductId(), stockBo);
			}
			return ServiceReturnUtils.success(skuStockMap);
		} else {
			return ServiceReturnUtils.success();
		}
	}
	
	/**
	 *  
	 * 根据，productIdList+店铺+仓库 的id 更新库存数量.(商家端 ：发货 & 取消两个操作调用)
	 * 确认发货--更新库存  :  冻结库存-- && 实际库存--; 
	 * @return
	 */
	@Override
	@Transactional(value = "transactionManager_order" , propagation=Propagation.REQUIRED)
	public ServiceReturnInfo updateStockForMerchant(List<SoSkuSummeryBo> sellOrderSkuBoList,
			  Long warehouseId,int tagetOrderStatus,EndMerchantUserBo endMerchantUserBo) {
		
		ProductStockExample productStockExample = new ProductStockExample();
		for(SoSkuSummeryBo  sellOrderSkuBo: sellOrderSkuBoList){
			Criteria stockQueryCriteria = productStockExample.createCriteria(); 
			productStockExample.or(stockQueryCriteria);
			stockQueryCriteria.andProductIdEqualTo(sellOrderSkuBo.getProductId());
			stockQueryCriteria.andShopIdEqualTo(sellOrderSkuBo.getShopId());
			stockQueryCriteria.andWarehouseIdEqualTo(warehouseId);
		}
		List<ProductStock> productStockList = productStockMapper.selectByExampleForUpdate(productStockExample);
		List<ProductStock> recordList= new ArrayList<ProductStock>(); 
		
		if (productStockList != null &&productStockList.size()>0 && (productStockList.size()== sellOrderSkuBoList.size())) {
			for( int i=0;i<productStockList.size();i++){
				ProductStock productStock =productStockList.get(i); 
				ProductStock record=new ProductStock();
				
				SoSkuSummeryBo relatedSkuBo=getSoSkuBo(productStock,sellOrderSkuBoList);
				Integer skuNum =  relatedSkuBo.getSkuNum();
				long realStockNumAfter = productStock.getRealStockNum()-skuNum;
				long realFrozenStockNumAfter = productStock.getRealFrozenStockNum()-skuNum;
				
				LOGGER.info("relatedSkuBo:"+JsonUtils.beanToJson(relatedSkuBo));
				LOGGER.info( " productId="+productStock.getProductId()
				+"，原冻结库存： RealFrozenStock="+productStock.getRealFrozenStockNum());
				
				LOGGER.info( " productId="+productStock.getProductId()
				+"，目标冻结库存： RealFrozenStock="+realFrozenStockNumAfter);
				//冻结--
				if( realFrozenStockNumAfter<0){
					LOGGER.error("sku冻结库存数量错误， stockId=" +productStock.getId());
					return ServiceReturnUtils.error(ServiceReturnCodes.SKU_REAL_STOCK_ERROR);
				}else{
					record.setRealFrozenStockNum(realFrozenStockNumAfter); 	
				}
				
				//真实--
				if(tagetOrderStatus==DbConstants.SO_STATUS_ALREADY_COMPLETED){
					LOGGER.info( " productId="+productStock.getProductId()
					+"; 原库存： RealStockNum="+productStock.getRealStockNum() );
					
					LOGGER.info( " productId="+productStock.getProductId()
					+"; 目标库存： RealStockNum="+realStockNumAfter );
					//发货同时更新真实库存
					 if(realStockNumAfter<0 ){
							LOGGER.error("sku真实库存数量错误， stockId=" +productStock.getId());
							return ServiceReturnUtils.error(ServiceReturnCodes.SKU_REAL_FREEZON_STOCK_ERROR);
					 }else{
						 record.setRealStockNum(realStockNumAfter); //sellOrderSkuBoList.
					 }
				 }
				
				record.setId( productStock.getId());
				recordList.add(record);
			}
			
			UpdateInfo updateInfo=new UpdateInfo();
			updateInfo.setUpdateTime(super.getTimeService().getDate());
			updateInfo.setUpdateUserId(endMerchantUserBo.getId());
			updateInfo.setUpdateUserName(endMerchantUserBo.getLoginName()); 
			
			int updateRows = productStockMapper.updateBatch(recordList, updateInfo);
			if(updateRows!=recordList.size()){
				LOGGER.error("库存批量更新失败不匹配. recordRows=" +recordList.size()+", updateRows="+updateRows);
				 throw new RuntimeException("库存批量更新失败不匹配. recordRows=" +recordList.size()+", updateRows="+updateRows);
				//return ServiceReturnUtils.error(ServiceReturnCodes.SKU_STOCK_BATCH_UPDATE_FAILED);
			}else {
				return ServiceReturnUtils.success();
			}
		} else {
			LOGGER.error("查询的库存记录数量和订单对应的库存记录不匹配.");
			return ServiceReturnUtils.error(ServiceReturnCodes.SKU_STOCK_NOT_MATCH_SKU_ORDER);
		}
	}
	/**
	 * 根据productStock找到对应的sosku.
	 * @param productStock
	 * @param sellOrderSkuBoList 
	 * @return
	 */
	private SoSkuSummeryBo getSoSkuBo(ProductStock productStock, List<SoSkuSummeryBo> sellOrderSkuBoList) {
		 for(SoSkuSummeryBo summeryBo:sellOrderSkuBoList){
			 if(summeryBo.getShopId().equals(productStock.getShopId()) 
					 && summeryBo.getProductId().equals(productStock.getProductId())){
				 return summeryBo;
			 }
		 }
		throw new RuntimeException("无法找到对应的so");
	}

	/*
	 * 修改库存 
	 */
	@Override
	public ServiceReturnInfo updateStock(EndMerchantUserBo endMerchantUserBo, ProductSkuBo productSkuBo, Long realStockNum) {
		//查询有没有
		ProductStockExample productStockExample = new ProductStockExample();
		Criteria criteria = productStockExample.createCriteria();
		criteria.andShopIdEqualTo(productSkuBo.getShopId());
		criteria.andProductIdEqualTo(productSkuBo.getProductId());
		List<ProductStock> productStockList = productStockMapper.selectByExample(productStockExample);
		ProductStock productStock=null;
		if (productStockList != null && productStockList.size() > 0) {
			productStock = productStockList.get(0);
		} else {
			LOGGER.error("所修改的商品不存在");
			return ServiceReturnUtils.error(ServiceReturnCodes.SKU_NOT_EXIST_EXCEPTION);
		}
		//验证是否小于冻结库存
		if(productStock.getRealFrozenStockNum()>realStockNum) {
			LOGGER.error("所修改的商品的冻结库存小于修改后的库存");
			return ServiceReturnUtils.error(ServiceReturnCodes.SKU_STOCK_NUM_REAL_LESS_THAN_FROZEN);
		}
		
		ProductStock record=new ProductStock();
		record.setUpdateTime(timeService.getDate());
		record.setUpdateUserId(endMerchantUserBo.getId());
		record.setUpdateUserName(endMerchantUserBo.getLoginName());
		record.setRealStockNum(realStockNum);
		int result=productStockMapper.updateByExampleSelective(record, productStockExample);
		if (result>0) {
			return ServiceReturnUtils.success();
		} else {
			LOGGER.error("修改失败");
			return ServiceReturnUtils.error(ServiceReturnCodes.SYSTEM_EXCEPTION);
		}
	}

	@Override
	public ServiceReturnInfo deleteStock(EndMerchantUserBo endMerchantUserBo, Long shopId, Long productId) {
		
		ProductStockExample productStockExample = new ProductStockExample();
		Criteria criteria = productStockExample.createCriteria();
		criteria.andShopIdEqualTo(shopId);
		criteria.andProductIdEqualTo(productId);
		int deleteCount = productStockMapper.deleteByExample(productStockExample);
		if(deleteCount ==1)  {
			return ServiceReturnUtils.success();
		} else {
			return ServiceReturnUtils.error(ServiceReturnCodes.SYSTEM_EXCEPTION);
		}
	}

}
